/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.protype.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import vip.xiaonuo.core.consts.SymbolConstant;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.factory.TreeBuildFactory;
import vip.xiaonuo.core.pojo.node.AntdBaseTreeNode;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.fieldconfig.entity.FieldConfig;
import vip.xiaonuo.modular.fieldconfig.service.FieldConfigService;
import vip.xiaonuo.modular.pro.entity.Pro;
import vip.xiaonuo.modular.pro.service.ProService;
import vip.xiaonuo.modular.protype.entity.ProType;
import vip.xiaonuo.modular.protype.enums.ProTypeExceptionEnum;
import vip.xiaonuo.modular.protype.mapper.ProTypeMapper;
import vip.xiaonuo.modular.protype.param.ProTypeParam;
import vip.xiaonuo.modular.protype.service.ProTypeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.util.AutoCode;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 产品类型表service接口实现类
 *
 * @author lixingda
 * @date 2022-05-20 14:01:44
 */
@Service
public class ProTypeServiceImpl extends ServiceImpl<ProTypeMapper, ProType> implements ProTypeService {
    @Resource
    private ProService proService;
    @Resource
    private FieldConfigService fieldConfigService;

    @Override
    public PageResult<ProType> page(ProTypeParam proTypeParam) {
        QueryWrapper<ProType> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(proTypeParam)) {

            // 根据编码 查询
            if (ObjectUtil.isNotEmpty(proTypeParam.getCode())) {
                queryWrapper.lambda().like(ProType::getCode, proTypeParam.getCode());
            }
            // 根据名称 查询
            if (ObjectUtil.isNotEmpty(proTypeParam.getName())) {
                queryWrapper.lambda().like(ProType::getName, proTypeParam.getName());
            }
            // 根据父级 查询
            if (ObjectUtil.isNotEmpty(proTypeParam.getPid())) {
                queryWrapper.nested(item -> {
                    //查询包括自身，Pid实际为自身id
                    item.lambda().eq(ProType::getId, proTypeParam.getPid()).
                            or().
                            like(ProType::getPids, proTypeParam.getPid());
                });
            }
            // 根据备注 查询
            if (ObjectUtil.isNotEmpty(proTypeParam.getRemarks())) {
                queryWrapper.lambda().like(ProType::getRemarks, proTypeParam.getRemarks());
            }
            //根据动态字段 查询
            if (ObjectUtil.isNotEmpty(proTypeParam.getJosn())) {
                //调用动态字段查询方法
                proService.dynamicFieldQuery("dw_pro_type", queryWrapper, proTypeParam.getJosn());
            }
        }
//        queryWrapper.lambda().orderByAsc(ProType::getSort);
        queryWrapper.orderByDesc("n.create_time");
        return new PageResult<>(baseMapper.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<ProType> list(ProTypeParam proTypeParam) {
        return this.list();
    }

    @Override
    public void add(ProTypeParam proTypeParam) {
        final String code = proTypeParam.getCode();
        if (ObjectUtil.isNull(code) || ObjectUtil.isEmpty(code)) {
            proTypeParam.setCode(AutoCode.getCodeByService("dw_pro_type", this.getClass(), 0));
        }
        //校验参数，检查是否存在相同的名称和编码
        checkParam(proTypeParam, false);
        //将json转换为json字符串
        String jsonToString = JSONArray.toJSON(proTypeParam.getJosn()).toString();
        proTypeParam.setJosn(jsonToString);
        //参数copy到实体类中进行保存
        ProType proType = new ProType();
        BeanUtil.copyProperties(proTypeParam, proType);
        this.fillPids(proType);
        this.save(proType);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<ProTypeParam> proTypeParamList) {
        // 储存需要删除的的条件
        QueryWrapper<ProType> proTypeQueryWrapper = new QueryWrapper<>();
        // 创建一个Map key 为产品类型id，value为该产品类型下所有的产品
        List<Pro> proList = proService.list();
        Map<Long,List<Pro>> proMap = proList.stream().collect(Collectors.groupingBy(Pro::getProTypeId));
        // 创建一个Map key 为产品类型id，value为该产品类型下所有的产品
        List<ProType> proTypeeList = this.list();
        Map<Long,ProType> proTypeMap = proTypeeList.stream().collect(Collectors.toMap(ProType::getId,a->a,(k1,k2)->k1));
        proTypeParamList.forEach(proTypeParam -> {
            if (ObjectUtil.isNotNull(proMap.get(proTypeParam.getId()))){
                throw new ServiceException(8, "【" + proTypeMap.get(proTypeParam.getId()).getName() + "】下存在所属产品，不可删除！");
            }
            //调用方法，根据id查询当前产品类型数据
            ProType proType = proTypeMap.get(proTypeParam.getId());
            Long id = proType.getId();
            //根据节点id获取所有子节点id集合
            List<Long> childIdList = this.getChildIdListById(id);
            //如果该产品类型下存在子类型，则不可删除
            if (childIdList.size() >= 1) {
                throw new ServiceException(7, "【" + proType.getName() + "】下存在子类型，不可删除！");
            }
            proTypeQueryWrapper.lambda().eq(ProType::getId,proTypeParam.getId()).or();
        });
        this.remove(proTypeQueryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ProTypeParam proTypeParam) {
        //调用方法，根据id查询当前产品类型数据
        ProType proType = this.queryProType(proTypeParam);
        //校验参数，检查是否存在相同的名称和编码
        checkParam(proTypeParam, true);
        BeanUtil.copyProperties(proTypeParam, proType);
        //避免空{}不能存入Josn
        if (ObjectUtil.isEmpty(proTypeParam.getJosn())) {
            proType.setJosn(JSONArray.toJSON("{}"));
        }
        //将js值转换为Josn
        if (ObjectUtil.isNotEmpty(proTypeParam.getJosn())) {
            String josnToString = JSONArray.toJSON(proTypeParam.getJosn()).toString();
            proType.setJosn(josnToString);
        }
        this.fillPids(proType);
        //将所有子的父id进行更新
        List<Long> childIdListById = this.getChildIdListById(proType.getId());
        childIdListById.forEach(subChildId -> {
            ProType child = this.getById(subChildId);
            ProTypeParam childParam = new ProTypeParam();
            BeanUtil.copyProperties(child, childParam);
            this.edit(childParam);
        });
        this.updateById(proType);
    }

    @Override
    public ProType detail(ProTypeParam proTypeParam) {
        return this.queryProType(proTypeParam);
    }

    /**
     * 获取产品类型表
     *
     * @author lixingda
     * @date 2022-05-20 14:01:44
     */
    private ProType queryProType(ProTypeParam proTypeParam) {
        ProType proType = this.getById(proTypeParam.getId());
        if (ObjectUtil.isNull(proType)) {
            throw new ServiceException(ProTypeExceptionEnum.NOT_EXIST);
        }
        return proType;
    }

    @Override
    public void export(ProTypeParam proTypeParam) {
        List<ProType> list = this.list(proTypeParam);
        PoiUtil.exportExcelWithStream("SnowyProType.xls", ProType.class, list);
    }

    @Override
    public List<AntdBaseTreeNode> tree(ProTypeParam proTypeParam) {
        List<AntdBaseTreeNode> treeNodeList = CollectionUtil.newArrayList();
        LambdaQueryWrapper<ProType> queryWrapper = new LambdaQueryWrapper<>();
        //根据排序升序排列，序号越小越在前
        queryWrapper.orderByAsc(ProType::getSort);
        //按AntdBaseTreeNode要求构建树形的数据结构
        this.list(queryWrapper).forEach(proType -> {
            AntdBaseTreeNode proTreeNode = new AntdBaseTreeNode();
            proTreeNode.setId(proType.getId());
            proTreeNode.setParentId(proType.getPid());
            proTreeNode.setTitle(proType.getName());
            proTreeNode.setValue(String.valueOf(proType.getId()));
            proTreeNode.setWeight(proType.getSort());
            treeNodeList.add(proTreeNode);
        });


        return new TreeBuildFactory<AntdBaseTreeNode>().doTreeBuild(treeNodeList);
    }


    /**
     * 根据节点id获取所有父节点id集合，不包含自己
     *
     * @author xuyuxiang
     * @date 2020/4/6 14:53
     */
    private List<Long> getProTypeById(Long id) {
        List<Long> resultList = CollectionUtil.newArrayList();
        ProType proType = this.getById(id);
        String pids = proType.getPids();
        String pidsWithRightSymbol = StrUtil.removeAll(pids, SymbolConstant.LEFT_SQUARE_BRACKETS);
        String pidsNormal = StrUtil.removeAll(pidsWithRightSymbol, SymbolConstant.RIGHT_SQUARE_BRACKETS);
        String[] pidsNormalArr = pidsNormal.split(SymbolConstant.COMMA);
        for (String pid : pidsNormalArr) {
            resultList.add(Convert.toLong(pid));
        }
        return resultList;
    }


    /**
     * 校验参数，检查是否存在相同的名称和编码
     *
     * @author xuyuxiang
     * @date 2020/3/25 21:23
     */
    private void checkParam(ProTypeParam proTypeParam, boolean isExcludeSelf) {
        Long id = proTypeParam.getId();
        String name = proTypeParam.getName();
        String code = proTypeParam.getCode();
        Long pid = proTypeParam.getPid();

        //如果父id不是根节点
        if (!pid.equals(0L)) {
            ProType pPro = this.getById(pid);
            if (ObjectUtil.isNull(pPro)) {
                //父机构不存在
                throw new ServiceException(ProTypeExceptionEnum.ORG_NOT_EXIST);
            }
        }

        // isExcludeSelf为true代表是编辑，父id和自己的id不能一致
        if (isExcludeSelf) {
            if (proTypeParam.getId().equals(proTypeParam.getPid())) {
                throw new ServiceException(ProTypeExceptionEnum.ID_CANT_EQ_PID);
            }

            // 如果是编辑，父id不能为自己的子节点
            List<Long> childIdListById = this.getChildIdListById(proTypeParam.getId());
            if (ObjectUtil.isNotEmpty(childIdListById)) {
                if (childIdListById.contains(proTypeParam.getPid())) {
                    throw new ServiceException(ProTypeExceptionEnum.PID_CANT_EQ_CHILD_ID);
                }
            }
        }

        LambdaQueryWrapper<ProType> queryWrapperByName = new LambdaQueryWrapper<>();
        queryWrapperByName.eq(ProType::getName, name);

        LambdaQueryWrapper<ProType> queryWrapperByCode = new LambdaQueryWrapper<>();
        queryWrapperByCode.eq(ProType::getCode, code);
        //如果是编辑，校验名称编码时排除自身
        if (isExcludeSelf) {
            queryWrapperByName.ne(ProType::getId, id);
            queryWrapperByCode.ne(ProType::getId, id);
        }

        int countByName = this.count(queryWrapperByName);
        int countByCode = this.count(queryWrapperByCode);

        if (countByName >= 1) {
            throw new ServiceException(ProTypeExceptionEnum.ORG_NAME_REPEAT);
        }
        if (countByCode >= 1) {
            throw new ServiceException(ProTypeExceptionEnum.ORG_CODE_REPEAT);
        }
    }


    /**
     * 根据节点id获取所有子节点id集合
     *
     * @author xuyuxiang
     * @date 2020/3/26 11:31
     */
    @Override
    public List<Long> getChildIdListById(Long id) {
        List<Long> childIdList = CollectionUtil.newArrayList();
        LambdaQueryWrapper<ProType> queryWrapper = new LambdaQueryWrapper<>();
        //查询为节点id子集的数据
        queryWrapper.like(ProType::getPids, SymbolConstant.LEFT_SQUARE_BRACKETS + id +
                SymbolConstant.RIGHT_SQUARE_BRACKETS);
        this.list(queryWrapper).forEach(proType -> childIdList.add(proType.getId()));
        return childIdList;
    }


    /**
     * 填充父ids
     *
     * @author xuyuxiang
     * @date 2020/3/26 11:28
     */
    private void fillPids(ProType proType) {
        //如果是一级菜单，则添加[0]
        if (proType.getPid().equals(0L)) {
            proType.setPids(SymbolConstant.LEFT_SQUARE_BRACKETS +
                    0 +
                    SymbolConstant.RIGHT_SQUARE_BRACKETS +
                    SymbolConstant.COMMA);
        } else {
            //获取父类型数据
            ProType pProType = this.getById(proType.getPid());
            //将父类型的所有父类中拼接上自身的id，即为当前添加类型的所有父类
            proType.setPids(pProType.getPids() +
                    SymbolConstant.LEFT_SQUARE_BRACKETS + pProType.getId() +
                    SymbolConstant.RIGHT_SQUARE_BRACKETS +
                    SymbolConstant.COMMA);
        }
    }
}
